package com.youshang.protobuf.client;

import com.youshang.protobuf.MyStudent;
import com.youshang.protobuf.common.Command;
import com.youshang.protobuf.common.Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 *
 * @author youshang
 * @date 2021/08/12 22:07
 **/
public class PbClientHandle extends SimpleChannelInboundHandler<MyStudent.Student> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyStudent.Student msg) throws Exception {
        System.out.println("收到的服务器消息:"+msg.toString());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        MyStudent.Student build = MyStudent.Student.newBuilder().setAge(23).setName("李四").setSex("女").build();
        //ctx.channel().writeAndFlush(build);
        ctx.channel().writeAndFlush(createData("clientId", Command.CommandType.AUTH_BACK, "客户端Id是"+"clientId"+"的建立连接请求success！").build());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }


    /** 构建不同类型的数据 基于protobuff
     * @Author: myzf
     * @Date: 2019/2/23 13:25
     * @param
     */
    private Message.MessageBase.Builder createData(String clientId, Command.CommandType cmd, String data){
        Message.MessageBase.Builder msg = Message.MessageBase.newBuilder();
        msg.setClientId(clientId);
        msg.setCmd(cmd);
        msg.setData(data);
        return msg;
    }
}
